﻿using HaiFengShop.Entity;
using HaiFengShop.ORM;
using HaiFengShop.ORM.Models;
using HaiFengShop.Tools;
using HaiFengShop.Tools.Utils;
using HaiFengShop.Tools.WeChat;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace HaiFengShop.Service
{
    public class AuthService : BaseServer<tb_user>
    {
        private readonly ConfigExtensions configExtensions;
        private readonly ResponseMessage res;
        public AuthService(ConfigExtensions configExtensions,
            ResponseMessage responseMessage,
             SugarDbContext sugarDbContext) : base(sugarDbContext.Db)
        {
            this.configExtensions = configExtensions;
            this.res = responseMessage;
        }
        /// <summary>
        /// 后台程序登陆
        /// </summary>
        /// <param name="DTOUser">后台用户信息</param>
        /// <returns></returns>
        //public ResponseMessage LoginByWeb(string username, string password)
        //{
        //    try
        //    {
        //        var admin = Context.Queryable<tb_admin>()
        //            .Where(s => s.username == username)
        //            .First();
        //        if (admin == null)
        //        {
        //            res.errmsg = "用户名或密码不正确!";
        //            res.errno = 400;
        //            return res;
        //        }
        //        password = Utility.EncryptString(password + admin.password_salt, Utility.EncryptorType.MD5);
        //        if (!admin.password.ToUpper().Equals(password))
        //        {
        //            res.errmsg = "用户名或密码不正确!";
        //            res.errno = 400;
        //            return res;
        //        }
        //        string clientIp = IPHelper.getRealIPAddress;
        //        admin.last_login_ip = clientIp;
        //        admin.last_login_time = (int)WebConfig.ConvertToUnixTimestamp(DateTime.Now);

        //        string token = Utility.EncryptString(username + password + admin.password_salt, Utility.EncryptorType.MD5);

        //        dynamic ddd = new
        //        {
        //            token = token,
        //            userInfo = new DTOUser()
        //            {
        //                id = admin.id,
        //                username = admin.username
        //            }
        //        };
        //        res.data = ddd;
        //        return res;
        //    }
        //    catch (Exception ex)
        //    {
        //        res.errmsg = ex.Message;
        //        res.errno = 400;
        //        return res;
        //    }
        //}

        /// <summary>
        /// 微信登录
        /// </summary>
        /// <param name="code">登录Code</param>
        /// <param name="userinfo">登录用户</param>
        /// <returns></returns>
        public async Task<ResponseMessage> LoginByWeixin(Root root)
        {

            string code = root.code;
            DTOUserInfo fullUserInfo = root.userInfo;
            UserInfo userInfo = fullUserInfo.userInfo;
            double currentTime = DateTimeExtensions.ConvertToUnixTimestamp(DateTime.Now);
            string clientIp = ""; // 暂时不记录 ip test git

            string WxOpenAppId = configExtensions.GetConfig("WxOpenAppId");
            string WxOpenAppSecret = configExtensions.GetConfig("WxOpenAppSecret");

            OpenIdModel om = await WeChatOpenIdInfo.GetXCXOpenIdInfo(code, WxOpenAppId, WxOpenAppSecret);
            if (string.IsNullOrEmpty(om?.openid))
            {
                res.errmsg = "登录失败";
                res.errno = -1;
                return res;
            }

            // 根据openid检查用户是否存在数据库
            // 存在就更改登录时间，IP地址，不存在就插入进去
            tb_user tu = Context.Queryable<tb_user>()
                 .Where(s => s.weixin_openid == om.openid)
                 .First();
            int is_new = 0;
            int id = 0;
            if (tu == null)
            {
                tu = new tb_user()
                {
                    username = "微信用户" + Guid.NewGuid().ToString("N").ToUpper(),
                    password = om.openid,
                    weixin_openid = om.openid,
                    register_time = (int)currentTime,
                    register_ip = clientIp,
                    last_login_ip = clientIp,
                    last_login_time = (int)currentTime,
                    birthday = 0,
                    mobile = "",
                    name = "",
                    name_mobile = 0,
                    avatar = userInfo.avatarUrl,
                    gender = userInfo.gender,
                    country = userInfo.country,
                    province = userInfo.province,
                    city = userInfo.city,
                    nickname = userInfo.nickName
                };
                is_new = 1;
                id = InsertReturnIdentity(tu);
            }
            else
            {
                tu.last_login_ip = clientIp;
                tu.last_login_time = (int)currentTime;
                tu.avatar = userInfo.avatarUrl;
                tu.nickname = userInfo.nickName;
                tu.country = userInfo.country;
                tu.city = userInfo.city;
                Update(tu);
                id = tu.id;
            }
            var jwtToken = new GenericJwtToken
            {
                Uid = 1,
                UserName = tu.nickname,
                Expires = DateTime.Now.AddHours(2)
            };

            dynamic ddd = new
            {
                token = AuthJwtEncoder.Encode(jwtToken),//加密登录信息
                userInfo = new tb_user()
                {
                    id = id,
                    username = tu.username,
                    nickname = tu.nickname,
                    gender = tu.gender,
                    avatar = tu.avatar
                },
                jwtToken.Expires,
                is_new
            };
            res.data = ddd;
            return res;
        }
    }
}
